import {getMonth, getYear, getDate} from "date-fns";
import React from 'react';
import DateFnsUtils from '@date-io/date-fns';
import { KeyboardDatePicker, MuiPickersUtilsProvider } from '@material-ui/pickers'

import { Button, Backdrop, CircularProgress, Snackbar, Card, CardActionArea, CardContent,CardActions,CardMedia } from '@material-ui/core'
import zh from 'date-fns/locale/zh-CN'
import axios from 'axios';
import Item from "./chat/item";
import { backendServer, authServer, default as globalData } from "./common/global";
import './home.scss';

export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            oneday: new Date((new Date().getTime() - 3 * 24 * 60 * 60 * 1000)),
            displayData: [],
            userInfo: {des: 'version1'},
            loadingInfo: {
                isLoading: true,
                tip: '加载中...',
            },
            tip: {
                isOpen: false,
                message: '',
            },
        }
    }
    componentDidMount() {
        this.getOAuthInfo();
    }
    closeTip = () => {
        this.setState({tip: {isOpen: false, message: ''}});
    }
    showTip = (message) => {
        this.setState({tip: {isOpen: true, message}});
    }
    closeLoading = (err) => {
        if (err) {
           this.showTip(err);
        }
        this.setState({loadingInfo: {isLoading: false, tip: ''}})
    }
    handleDateChange = (choosedDate) => {
        console.log("选择了:", choosedDate)
        this.setState({
            oneday: choosedDate
        }, () => {
            this.queryDate(choosedDate);
        })
    }
    queryDate = (date) => {
        let year = getYear(date);
        let day = getDate(date);
        let month = getMonth(date) + 1;
        axios.get(`${backendServer}/ourrecord/oneday/${year}/${month}/${day}`)
            .then( resp => {
                let data = resp.data;
                if (data) {
                    this.setState({displayData: data})
                }
            })
    }
    renderMessage = (dataArr) => {
        return dataArr.map(data => {
            return <Item data={data} key={data.id}/>
        })
    }
    getOAuthInfo = () => {
        // alert(JSON.stringify(globalData.oauthData))
        this.setState({loadingInfo: {isLoading: true, tip: '微信授权中'}})
        axios.get(`${authServer}/authorize/wechat/access/`, {
            params: {
                authCode: globalData.oauthData.code,
            }
        }).then(resp => {
            let {data} = resp;
            // alert(JSON.stringify(data));
            if(data.openid) {
                globalData.wxInfo.openid = data.openid;
                this.getUserInfo(data.openid);
            } else {
                throw Error(data.errmsg ? data.errmsg : '服务器异常');
            }
        }).catch(e => {
            this.closeLoading(e.message ? e.message : "error!");
        })
    }
    getUserInfo = (openid) => {
        this.setState({loadingInfo: {isLoading: true, tip: '鉴别身份中'}})
        axios.get(`${authServer}/authorize/wechatfunc/userinfo`, {
            params: {
                openid: openid
            }
        }).then(resp => {
            let {data} = resp;
            if (!data.errmsg) {
                this.setState({userInfo: data});
                this.setState({loadingInfo: {isLoading: false, tip: ''}});
            } else {
                throw Error(data.errmsg);
            }
        }).catch(e => {
            this.closeLoading(e.message ? e.message : "error!");
        })
    }
    learnMore = () => {
        this.showTip('祝福我们吧👈🌿')
    }

    render() {
        return <div>
            <div className="home-header">
                {
                    globalData.whiteList.indexOf(this.state.userInfo.nickname) !== -1 ?
                    <MuiPickersUtilsProvider utils={DateFnsUtils} locale={zh}>
                        <KeyboardDatePicker
                            margin="normal"
                            id="date-picker-dialog"
                            label="在某天"
                            format="yyyy年MM月dd日"
                            value={this.state.oneday}
                            onChange={this.handleDateChange}
                            KeyboardButtonProps={{
                                'aria-label': '是的，这天',
                            }}
                        />
                    </MuiPickersUtilsProvider>
                    :
                    <Card>
                        <CardActionArea>
                            <CardMedia
                                style={{height: '100px'}}
                                image="https://s3.ax1x.com/2021/03/15/6r3WkV.jpg"
                                title="ssmell"
                            />
                            <CardContent>
                                <div>不好意思你不是🐷,感谢光临😜</div>
                            </CardContent>
                        </CardActionArea>
                        <CardActions>
                            <Button size="small" color="primary" onClick={this.learnMore}>了解更多</Button>
                        </CardActions>
                    </Card>
                }
                {/*<Button color="primary" variant="contained" onClick={this.getOAuthInfo}>GetInfo</Button>*/}
            </div>
            <div style={{ overflowY: 'auto'}}>
                {this.renderMessage(this.state.displayData)}
            </div>
            <Backdrop open={this.state.loadingInfo.isLoading} >
                <div className="loading-tip">
                    <CircularProgress color='inherit'/>
                    <div style={{height: '10px'}}/>
                    {this.state.loadingInfo.tip}
                </div>
            </Backdrop>
            <Snackbar
                anchorOrigin={{vertical: 'top', horizontal: 'center'}}
                open={this.state.tip.isOpen}
                autoHideDuration={5210}
                onClose={this.closeTip}
                message={this.state.tip.message}
            ></Snackbar>
        </div>
    }

}